package cn.yanglq.Rss.web.controller;

import cn.yanglq.Rss.task.JobTask;
import cn.yanglq.Rss.web.WebConsts;
import cn.yanglq.Rss.web.common.vo.ApiResult;
import cn.yanglq.Rss.web.dao.MailSetMapper;
import cn.yanglq.Rss.web.model.JobSet;
import cn.yanglq.Rss.web.model.MailSet;
import cn.yanglq.Rss.web.model.User;
import cn.yanglq.Rss.web.service.JobSetService;
import cn.yanglq.Rss.web.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by yanglq on 2017/6/8.
 */

@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {

    private String validMsg;// 验证结果消息
    @Autowired
    private UserService userService;
    @Autowired
    private JobSetService jobSetService;
    @Autowired
    private MailSetMapper mailSetMapper;

    @RequestMapping("loginPage")
    public String loginPage(HttpSession httpSession) {
        return "/login";
    }


    @RequestMapping
    public String loginPage2(HttpSession httpSession) {

        if (httpSession.getAttribute(WebConsts.SESSION_USERID) != null) {
            return "redirect:/main";
        }
        return "/login";
    }

    @RequestMapping(value = "/userLogout")
    public String logout(HttpSession httpSession) {

        httpSession.removeAttribute(WebConsts.SESSION_USERID);
        httpSession.removeAttribute(WebConsts.SESSION_USERTYPE);
        httpSession.invalidate();
        return "redirect:/login";
    }

    @RequestMapping(value = "/userLogin")
    @ResponseBody
    public ApiResult userLogin(
            @RequestParam(value = "name", required = true) String name,
            @RequestParam(value = "paw", required = true) String paw,
            @RequestParam(value = "captchaCode", required = true) String captchaCode,
            HttpServletRequest request, HttpSession httpSession) {

        ApiResult result = new ApiResult();
        if (!valid(name, paw, captchaCode, httpSession)) {
            result.setSuccess(false);
            result.setErrorcode(110);
            result.setMessage(validMsg);
            return result; //校验通过返回成功
        }

        httpSession.setAttribute(WebConsts.SESSION_USERID, name);
//        httpSession.setAttribute(WebConsts.SESSION_USERTYPE, inf.getUtype());
        result.setSuccess(true);
        result.setErrorcode(0);
        result.setMessage("登录成功！");
        result.setDatas(httpSession.getServletContext().getContextPath()
                + "/main");


        List<JobSet> lists = jobSetService.selectjobInfos(name);
        if (lists != null) {
            for (JobSet job : lists
                    ) {
                String str = JobTask.buildTime(job);
                try {
                    MailSet set = mailSetMapper.selectByPrimaryKey(job.getSendid());
                    JobTask.doQuartz(str,set);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return result; //校验通过返回成功
    }

    private boolean valid(String name, String paw, String captchaCode, HttpSession httpSession) {

        //校验用户名密码
        // ……
        User user = userService.selectUserByUserId(name);

        if (user == null || !name.equals(user.getUserid())) {
            validMsg = "用户名或密码错误！";
            return false;
        }


        if (!DigestUtils.md5Hex(paw).equals(user.getPasswd())) {
            validMsg = "用户名或密码错误！";
            return false;
        }
        // ……


        //用户输入的验证码的值
        //校验验证码是否正确
        String kaptchaExpected = (String) httpSession
                .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if (captchaCode == null || !captchaCode.toLowerCase().equals(kaptchaExpected.toLowerCase())) {
            validMsg = "验证码错误！";
            return false;
        }
        return true;
    }

    @RequestMapping(value = "/updatePassword")
    public String updatePassword() {
        return "/userinfo/updatepwd";
    }

    @RequestMapping(value = "/userInfo")
    public ModelAndView userInfo() {
        String userid = findCurrentLoginid();
        ModelAndView mv = new ModelAndView();
        User user = userService.selectUserInfo(userid);
        mv.addObject("userInfoVo", user);
        mv.setViewName("/userinfo/userinfo");
        return mv;
    }
}
